package at.codebase.db.dao;

import static at.codebase.db.OfyService.ofy;

import java.util.List;

import at.codebase.core.log.LogTypes;
import at.codebase.db.entities.ELogMessage;
import at.codebase.db.entities.EUser;

import com.googlecode.objectify.cmd.Query;

public class ELogMessageDao {

	public static ELogMessage getLogMessageById(final long id) {
		return ofy().load().type(ELogMessage.class).id(id).get();
	}

	public static void saveLogMessage(ELogMessage msg) {
		// "now()" not necessary
		ofy().save().entity(msg);
	}

	public static List<ELogMessage> getLogMessages(final int offset,
			final int limit) {
		return ofy().load().type(ELogMessage.class).offset(offset).limit(limit)
				.order("-timestamp").list();
	}

	public static List<ELogMessage> getLogMessagesFilter(int logType,
			long userId, int offset, int limit) {
		Query<ELogMessage> query = ofy().load().type(ELogMessage.class);
		if(logType != LogTypes.ALL){
			query = query.filter("type", new Integer(logType));
		}
		if(userId > 0){
			query = query.filter("user", EUser.key(new Long(userId)));
		}
		return query.offset(offset).limit(limit).order("-timestamp").list();
	}

	public static int getLogMessageCount() {
		return ofy().load().type(ELogMessage.class).count();
	}

	public static int getLogMessageCountFilter(final int logType, final long userId) {
		Query<ELogMessage> query = ofy().load().type(ELogMessage.class);
		if(logType != LogTypes.ALL){
			query = query.filter("type", new Integer(logType));
		}
		if(userId > 0){
			query = query.filter("user", EUser.key(new Long(userId)));
		}
		return query.count();
	}
}
